'use strict';

const jwt = require('jsonwebtoken');

const Controller = require('../../core/common');

class SigninController extends Controller {

  async index() {
    this.success(123)
  }

  async show() {
    return this.success(123)
  }

  async create() {
    const { ctx, app } = this;

    const { code, nickName, ...body } = ctx.request.body;

    if (!code) ctx.throw(401, 'code为空');

    const results = await ctx.curl(
      `https://api.weixin.qq.com/sns/jscode2session?appid=${app.config.weappSDK.appId}&secret=${app.config.weappSDK.appSecret}&js_code=${code}&grant_type=authorization_code`, {
        dataType: 'json'
      }
    );
    const openId = results.data.openid;

    if (openId) {
      const defaults = { ...body, nickname: nickName, code };
      const data = await ctx.model.Users.findOrCreate({ defaults, where: { openId } });
      const [{ id }] = JSON.parse(JSON.stringify(data));

      let token = '';
      try {
        // token = jwt.sign({ foo: 'bar', id }, app.config.jwt.secret, { expiresIn: '7d' });
        token = app.jwt.sign({ id }, app.config.jwt.secret, { expiresIn: '7d' });
      } catch (e) {
        ctx.throw(500, '生成 Token失败！');
      }

      await app.redis.get('users').set('id_' + id, token);
      ctx.set('Authorization', `Bearer ${token}`);

      this.success({ ...defaults, token, code, openId, userId: id });
    } else {
      ctx.throw(500, '获取 openId失败！');
    }

    ctx.status = results.status;
  }

  async update() {
    // setDataValue
    this.success('update')
  }

}

module.exports = SigninController;